package edu.scau.mis.core.service;

import com.aliyun.oss.OSSClient;
import edu.scau.mis.core.config.OssConfig;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 向阿里云oss传送图片
 */
@Service
public class FileUploadService {

    @Autowired
    private OssConfig ossConfig;// 注入阿里云OSS基本配置类

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    // 允许上传文件(图片)的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};

    //获取文件名字
    private String getFilename(String ext, String date) {
        //为了避免图片重名，使用UUID来命名图片
        String uuid = UUID.randomUUID().toString();
        //组合filename
        String filename = ossConfig.getFileHost() + "/" + date + "/" +uuid + ext;
        return filename;
    }

    /**
     * 上传文件
     * @param multipartFile 文件(图片)
     * @return
     */
    public String uploadDocument(MultipartFile multipartFile){
        //拓展名
        String ext = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        //上传日期
        String date = sdf.format(new Date());
        //文件名字
        String filename = getFilename(ext, date);
        //上传路径
        String url = null;
        //创建阿里云oss文件服务器客户端
        OSSClient ossClient = new OSSClient(ossConfig.getEndPoint(), ossConfig.getKeyId(), ossConfig.getKeySecret());

        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (type.equals(ext)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {// 如果图片格式不合法
            return "图片格式错误";
        }
        try {
            ossClient.putObject(ossConfig.getBucketName(), filename, new ByteArrayInputStream(multipartFile.getBytes()));
            url = ossConfig.getUrlPrefix() + filename;
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            ossClient.shutdown();
        }
        return url;
    }

    /**
     * 上传图片
     * @param photoUrl 图片的本地路径
     * @return
     */
    public String uploadPhoto(String photoUrl){
        MultipartFile multipartFile = testOSSServiceImport(photoUrl);
        return uploadDocument(multipartFile);
    }

    /**
     * 将读取本地图片的FileInputStream转为CommonsMultipartFile 传给uploadDocument 进行图片上传
     * @param urlPath
     * @return
     */
    public MultipartFile testOSSServiceImport(String urlPath){
        File file = new File(urlPath);
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                MediaType.ALL_VALUE, true, file.getName());
        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        MultipartFile multi = new CommonsMultipartFile(fileItem);
        return multi;
    }


}
